jQuery(document).ready(function($) {

	$('[data-trigger]').off('click.OnCheck').on('click.OnCheck',function(){
		 var $url =  $(this).attr('url');
		 if($url){
		     window.location = $url;	 
		 };
		
	});
	$('[show-message-login]').on('click',function(e){
		e.preventDefault();
		showBoxInfo('Para realizar essa operação é preciso fazer o login');
	});
	
	
	$('[show-message-user-block]').on('click',function(e){
		e.preventDefault();
		showBoxInfo('Esse usuário não tem permissão para essa operação');
	});
	
	$('[getCondicoesVendas]').on('click',function(e){
		e.preventDefault();
		var $id = $(this).attr('data-id');
		$.fancybox.open({
			href : url_site+'home/get_condicoes_pagamento/'+$id,
			type : 'iframe',
			padding : 5
		});
	});
	
	
     $('.btn-ativar').on('click', 'a', function(e) {
         e.preventDefault();
         var $on = $(this).attr('activate');
         if ($on === 'true') {
             $(this).attr('activate', 'false').removeClass('on').addClass('off');
             $('.text-off').text('OFF');

         } else {
             $(this).attr('activate', 'true').removeClass('off').addClass('on');
             $('.text-off').text('ON');
         }
     });
	
	
	
        $('[role="search"]').on('click',function(){
              $('form#searchSite').trigger('submit');
        });
             

            $('.carousel').carousel({

                interval: 10000
            });
    
    $('a[href="#nodata"]').on('click', function(ev) {
        ev.preventDefault();
        var obj = $(this).offset(),
                pleft = obj.left,
                ptop = obj.top,
                obj_width = $(this).width(),
                obj_height = $(this).outerHeight();

        var markup = '<div class="tip-no-data-menu">' +
                ' Menu sem dados </div>';
        $(markup).appendTo('body').css({top: ptop + (obj_height / 5) + 'px', 'left': (obj_width + pleft) + 'px'}).fadeIn()
                .delay(1500).fadeOut();



    });

    $('a.btn-lance-option').on('click', function(e) {
        e.preventDefault();

        $('a.btn-lance-option').removeClass('active');
        $(this).addClass('active');

        var mul = $(this).attr('data-multiply');
        if (mul == '*') {


            $('#modalOpMultiply').remove();

            var mark = '<div class="modal fade" id="modalOpMultiply" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
                    '<div class="modal-dialog">' +
                    '<div class="modal-content">' +
                    '<div class="modal-header">' +
                    '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
                    '<h4 class="modal-title">&nbsp;</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '<div class="col-md-2">' +
                    form_input('option-multiply', OptionMultiply, 'class="form-control" maxlength="2"') +
                    '</div>' +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<button type="button" class="btn btn-primary" role="saveOptionMultiply">Salvar </button>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            $(mark).appendTo('body');
            $('#modalOpMultiply').modal();

            $('[role="saveOptionMultiply"]').on('click', function() {

                OptionMultiply = $('input[name="option-multiply"]').val();
                $('[data-dismiss="modal"]').trigger('click');
            });

        }


    });
    
    /*
    $('a[role="addLance"]').click(function(e) {
        e.preventDefault();
        var id = $(this).attr('lance-lote-id'),
                objCount = $('.clock-count-ativo-single[data-id="' + id + '"]'),
                sd = objCount.attr('data-count'),
                data = sd.split(' '),
                ar_date = data['0'].split('-'),
                ar_hour = data['1'].split(':'),
                sum_m = parseInt(ar_hour['1'], 10) + 3;
        sum_m = sum_m < 10 ? '0' + sum_m : sum_m;

        var hours = [ar_hour['0'], sum_m, ar_hour['2']].join(':'),
                data_c = ar_date.join('-'),
                countdownDate = [data_c, hours].join(' ');
        objCount.attr('data-count', countdownDate);


        var newYear = new Date(),
                minutes_sec = minutes * 60,
                inewYear = new Date(newYear.getFullYear(), newYear.getMonth(), newYear.getDate(), newYear.getHours(), newYear.getMinutes() , newYear.getSeconds() + 30);


        if (onTicker['painel-data-' + id] < minutes_sec) {
            //$('#painel-online-' + id).removeClass('red');
            $('.clock-count-ativo-single[data-id="' + id + '"]').countdown('option', {until: + 30} );

        }

    });
    
    */
    $('a[role="panelOnline"]').on('click', function(e) {
        e.preventDefault();

        popitup($(this).attr('href'));
    });

    function popitup(url) {

        LeftPosition = 0;
        TopPosition = 0;
        var sheight = parseInt(screen.height, 10);
        var swidth = parseInt(screen.width, 10);

        h = (sheight - (parseInt((sheight * 0.15), 10)));
        w = (swidth - (parseInt((swidth * 0.05), 10)));
        lefto = (parseInt((swidth * 0.05), 10));
        lefto = lefto / 2;
        topto = (parseInt((sheight * 0.05), 10));
        topto = topto / 2;

        settings = 'height=' + h + ',width=' + w + ',top=' + topto + ',left=' + lefto + ',scrollbars=yes,resizable=yes,toolbar=no,status=no,menu=no, directories=no,titlebar=no,location=no,addressbar=no'

        newwindow = window.open(url, '', settings);
        if (window.focus) {
            newwindow.focus()
        }
        return false;
    }
    $('label.required').append(' <strong>*</strong');
    // save news letter
    $('.message-is-activation').delay(15000).slideUp();
    /*
    $('a[role="addNewsLetter"]').on('click', function(event) {

        event.preventDefault();
        var markup_modal = '<div class="display-info-newsletter">Fique por dentro de nossas novidades, cadastre seu email para receber nosso email marketing com os principais assuntos do leiloar.net</div>' +
                '<form id="form-news-letter" action="' + url_site + 'add_news_letter' + '">' +
                '<div class="form-group">' +
                '<label>Nome</label>' +
                '<input type="text" name="name" placeholder="Digite seu nome" class="form-control " validation="required" />' +
                '</div>' +
                '<div class="form-group">' +
                '<label>Email</label>' +
                '<input type="text" name="email" placeholder="Digite seu email" class="form-control" validation="required|email" />' +
                '</div>' +
                '</form>';

        show_modal_box_leiloar(markup_modal);
        $('#form-news-letter').contactValidation({url: url_site + 'add_news_letter',
            ajaxSuccess: function(status, message, form) {

            },
            callbackBeforeCloseMessage: function(status, message, form) {
                if (status === false) {
                    $('button[name="imodalclose"]').trigger('click');
                }
            }
        });
        $('button[role="sendModal"]').off('click').on('click', function() {
            $('#form-news-letter').trigger('submit');
        });

    });*/
    function ajaxValidationCallback(status, form, json, options) {
        if (json.error === true) {
            $('<div class="label label-danger" style="display:none;">' + data.message + '</div>').appendTo('#form-news-letter').slideDown().delay(3000).slideUp();
        } else {
            $('<div class="label label-success" style="display:none;">' + data.message + '</div>').appendTo('#form-news-letter').slideDown().delay(3000).slideUp(500, function() {
                $('button[name="imodalclose"]').trigger('click');
            });
        }
    }
    
    $('a[role="previewCondicoes"]').on('click',function(e){
		e.preventDefault();
		 var id = $(this).attr('u-id'),
         leilao_id = $(this).attr('l-id');
	
		$.fancybox.open({
			href : url_site +'/habilitacao-'+leilao_id+'-'+id+'.html',
			padding : 5,
			type:'iframe'
		});
	});
    
    $('[has-habilitacao]').on('click',function(e){
		e.preventDefault();
		 var id = $(this).attr('u-id'),
        leilao_id = $(this).attr('l-id');
		$.fancybox.open({
			href : url_site +'/is-habilitacao-'+leilao_id+'-'+id+'.html',
			padding : 5,
			type:'iframe',
			autoSize: false,
			'width':400,
			'height':200
		});
	});
    
});

function acept_condition(data) {
    var data = data || {};

    $.ajax({
        url: url_site + 'addNewHabilitacao.html',
        type: 'post',
        dataType: 'json',
        data: data,
        success: function(data) {
            
            if (data.error == false) {
                
                $('button[role="onclose"]').trigger('click');
               // window.location =  
            }
            window.location = window.location.href;

        }
    });


}


function show_modal_box_leiloar(markup) {

    $('#modalNewsLetter').remove();

    var mark = '<div class="modal fade" id="modalNewsLetter" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
            '<h4 class="modal-title">&nbsp;</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            markup +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" role="onclose" class="btn btn-default" name="imodalclose" data-dismiss="modal">Fechar</button>' +
            '<button type="button" class="btn btn-primary" role="sendModal">Enviar </button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
    $(mark).appendTo('body');
    $('#modalNewsLetter').modal();
}

(function($, window, document, undefined) {

    var pluginName = 'contactValidation',
            defaults = {
                url: '',
                messageBeforeForm: false,
                ajaxSuccess: function(status, message, form) {
                },
                callbackBeforeCloseMessage: function(status, message, form) {
                },
                isAjax: true
            };

    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);

        this._name = pluginName;
        this._defaults = defaults;

        this.init();
    }


    Plugin.prototype = {
        init: function() {

            var self = this, op = {};
            $(this.element).find('input,select,textarea').each(function() {
                var validation = $(this).attr('validation'),
                        name = $(this).attr('name'),
                        type = $(this).attr('type') || 'text';
                if (validation != undefined) {
                    op[name] = {'name': name, 'regex': validation, 'type': type};
                }
                $(this).on('focusin', function() {
                    self.removeDisplayError(this);
                });
            });


            $(this.element).data('items_validate', op);
            if (self.options_form.messageBeforeForm == false) {
                $(this.element).prepend('<div class="onDisplayErrorFormValidate"></div>').addClass('contactValidationForm');
            } else {
                $(this.element).append('<div class="onDisplayErrorFormValidate"></div>').addClass('contactValidationForm');
            }

            $(this.element).on('submit', function(event) {
                self.send(event, this)
            });

        },
        options_form: {},
        send: function(event, obj) {



            this.execute(this, event);
            var options = this.options, self = this;


            if ($(this.element).data('erros') == 0) {

                if (options.isAjax == true) {
                    event.preventDefault();
                    $.ajax({
                        url: options.url,
                        type: 'post',
                        data: self.prepare_data(),
                        dataType: 'json',
                        beforeSend: function() {
                            $('.onDisplayErrorFormValidate').html('<div class="loading"> Aguarde...</div>');
                        },
                        success: function(data) {

                            options.ajaxSuccess(data.error, data.message, self.element);
                            //self.reset();
                            var type = 'danger';
                            if (data.error == false) {
                                self.reset();
                                type = 'success';
                            }

                            $('.onDisplayErrorFormValidate > .loading').remove();
                            $('<div style="display:none;" class="label label-' + type + ' validateMessageForm">' + data.message + '</div>').appendTo('.onDisplayErrorFormValidate');
                            $('.validateMessageForm').slideDown().delay(2000).slideUp(500, function() {
                                options.callbackBeforeCloseMessage(data.error, data.message, self.element);
                            });

                        }
                    });
                } else {


                }

            } else {

                event.preventDefault();
            }





        },
        execute: function(obj, event) {


            var opt = $(this.element).data('items_validate'), self = this, icalls = {}, errors = {}, form = this.element;
            for (var i in opt) {
                var opp = opt[i],
                        icalls = self.detecte_call(opp['regex']),
                        name = opp['name'],
                        type = opp['type'],
                        methods = icalls.callbacks,
                        max = methods.length,
                        error = {};

                for (var j = 0; j < max; j += 1) {
                    var ival = $(form).find('input[name="' + name + '"],select[name="' + name + '"],textarea[name="' + name + '"]').val(),
                            ifunc = methods[j];
                    if (self.apply_validate(ival, ifunc)) {
                        error[ifunc] = self.apply_validate(ival, ifunc);
                    }
                }
                errors[name] = error;

            }


            var errors_form = 0;
            for (var l in errors) {

                var data = errors[l], message = '', name = l, count = 0, num_errors = 0;
                element = $(form).find('input[name="' + name + '"],select[name="' + name + '"],textarea[name="' + name + '"]');
                this.removeDisplayError(element);
                for (var f in data) {
                    var im = data[f];
                    if (num_errors) {
                        message += '<br/>';
                    }
                    if (im.error == true) {
                        message += im.message;
                        num_errors += 1;
                    }
                    count += 1;
                }


                if (num_errors > 0) {
                    self.addDisplayError(element, message);
                    var ep = $(element).offset();

                    errors_form += 1;

                }


            }

            $(this.element).data('erros', errors_form);


        },
        apply_validate: function(val, func) {
            var validate = this.validates, method = validate[func];
            if (typeof method == 'function') {
                return method(val);
            }
            return false;
        },
        detecte_call: function(str) {

            var dt = /\|/gi;
            if (dt.test(str)) {
                return {'callbacks': str.split('|')};
            }
            return {'callbacks': [str]};

        },
        reset: function() {

            $(this.element).find('input[type="text"],input[type="password"],input[type="checkbox"],input[type="radio"],textarea,select').each(function() {
                var type = $(this).attr('type');
                if (type == 'checkbox' || type == 'radio') {
                    $(this).attr('checked', false);
                } else {
                    $(this).val('');
                }


            });
        },
        prepare_data: function() {
            var rs = {};

            $(this.element).find('input[type="text"],input[type="password"],input[type="checkbox"],input[type="radio"],textarea,select').each(function() {
                var name = $(this).attr('name'), val = $(this).val();
                rs[name] = val;
            });

            return rs;

        }


        ,
        validates: {
            required: function(str) {
                str = new String(str);

                if (str.length > 0 && str != '') {
                    return {'error': false, 'message': ''};
                }

                return {'error': true, 'message': 'Campo é obrigatório'};

            },
            email: function(str) {
                var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm;

                if (str == '') {
                    return {'error': false, 'message': ''};
                }
                if (re.test(str)) {
                    return {'error': false, 'message': ''};
                }

                return {'error': true, 'message': 'Digite um email válido'};

            },
            celular: function(str) {
                var re = /\([0-9]{2}\)[9][5-9][0-9]{3}\-[0-9]{4}/igm;
                if (str == '') {
                    return {'error': false, 'message': ''};
                }
                if (re.test(str)) {
                    return {'error': false, 'message': ''};
                }

                return {'error': true, 'message': 'Digite um celular válido'};

            },
            fone: function(str) {
                var re = /\([0-9]{2}\)[2-5][0-9]{3}\-[0-9]{4}/igm;
                if (re.test(str) || str == '') {
                    return {'error': false, 'message': ''};
                }
                return {'error': true, 'message': 'Digite um telefone válido'};

            },
            cpf: function(cpf) {

                if (cpf == '')
                    return {'error': false, 'message': ''};
                var cpf = cpf.replace(/[^\d]+/g, ''), dig_num = false,
                        valid_dig_1 = false,
                        valid_dig_2 = false;




                // Elimina CPFs invalidos conhecidos
                if (cpf.length != 11 ||
                        cpf == "00000000000" ||
                        cpf == "11111111111" ||
                        cpf == "22222222222" ||
                        cpf == "33333333333" ||
                        cpf == "44444444444" ||
                        cpf == "55555555555" ||
                        cpf == "66666666666" ||
                        cpf == "77777777777" ||
                        cpf == "88888888888" ||
                        cpf == "99999999999")
                    dig_num = true;

                // Valida 1o digito
                add = 0;
                for (i = 0; i < 9; i ++)
                    add += parseInt(cpf.charAt(i)) * (10 - i);
                rev = 11 - (add % 11);
                if (rev == 10 || rev == 11)
                    rev = 0;
                if (rev != parseInt(cpf.charAt(9)))
                    valid_dig_1 = true;

                // Valida 2o digito
                add = 0;
                for (i = 0; i < 10; i ++)
                    add += parseInt(cpf.charAt(i)) * (11 - i);
                rev = 11 - (add % 11);
                if (rev == 10 || rev == 11)
                    rev = 0;
                if (rev != parseInt(cpf.charAt(10)))
                    valid_dig_2 = true;

                if (dig_num == false && valid_dig_1 == false && valid_dig_2 == false) {
                    return {'error': false, 'message': ''};
                }
                return {'error': true, 'message': 'Digite um cpf válido'};

            },
            cnpj: function(str) {


                if (str == '')
                    return {'error': false, 'message': ''};
                str = str.replace('.', '');
                str = str.replace('.', '');
                str = str.replace('.', '');
                str = str.replace('-', '');
                str = str.replace('/', '');
                cnpj = str;
                var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;

                digitos_iguais = 1;

                if (cnpj.length < 14 && cnpj.length < 15)
                    return {'error': true, 'message': 'Digite um cnpj válido'};
                for (i = 0; i < cnpj.length - 1; i++)
                    if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                    {
                        digitos_iguais = 0;
                        break;
                    }
                if (!digitos_iguais)
                {
                    tamanho = cnpj.length - 2
                    numeros = cnpj.substring(0, tamanho);
                    digitos = cnpj.substring(tamanho);
                    soma = 0;
                    pos = tamanho - 7;
                    for (i = tamanho; i >= 1; i--)
                    {
                        soma += numeros.charAt(tamanho - i) * pos--;
                        if (pos < 2)
                            pos = 9;
                    }
                    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
                    if (resultado != digitos.charAt(0))
                        return {'error': true, 'message': 'Digite um cnpj válido'};
                    tamanho = tamanho + 1;
                    numeros = cnpj.substring(0, tamanho);
                    soma = 0;
                    pos = tamanho - 7;
                    for (i = tamanho; i >= 1; i--)
                    {
                        soma += numeros.charAt(tamanho - i) * pos--;
                        if (pos < 2)
                            pos = 9;
                    }
                    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
                    if (resultado != digitos.charAt(1))
                        return {'error': true, 'message': 'Digite um cnpj válido'};
                    return {'error': false, 'message': ''};
                }
                else
                    return {'error': true, 'message': 'Digite um cnpj válido'};
            }



        },
        addDisplayError: function(element, message) {
            message = message || '';
            element = element || false;
            if (element !== false) {
                //this.removeDisplayError(element);

                var name = $(element).attr('name'),
                        eposition = $(element).offset(),
                        e_widht = $(element).width(),
                        p_left = (eposition.left + e_widht),
                        p_top = (eposition.top + 3),
                        zIndexEl = $(element).css('z-index'),
                        display = '<span style="left:' + Math.ceil(p_left) + 'px; top:' + Math.ceil(p_top) + 'px; z-index:' + (zIndexEl + 1) + ';" class="validate-field-' + name + ' displayErrorOptionsMeta">'
                        + message
                        + '</span>';
                $(display).appendTo('body').fadeIn();
                $(element).addClass(name + '-novalid').addClass('fieldErrorOptionsMeta');

            }




        },
        removeDisplayError: function(element) {
            var name = $(element).attr('name');
            $(element).removeClass(name + '-novalid').removeClass('fieldErrorOptionsMeta');

            $('.validate-field-' + name + '.displayErrorOptionsMeta').fadeOut(function() {
                $(this).remove()
            });
        }



    };
    function call_func_array(fn, args) {
        fn = (typeof fn == "function") ? fn : window[fn];  // Allow fn to be a function object or the name of a global function

        console.log(fn);
        return fn.apply(this, args || []);  // args is optional, use an empty array by default
    }


    $.fn[pluginName] = function(options) {

        if (!$.data(this, 'plugin_' + pluginName)) {
            return $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
        }
    }



})(jQuery, window, document);

function showBoxInfo(info){
	
	$.fancybox(
			'<div><img src="/public/images/logo.png" width="160px"/><h5>'+info+'</h5></div>',
			{
	        	'autoDimensions'	: false,
				'width'         		: 200,
				'height'        		: 50,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			
			}
		);
	
}